package net.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端tcp连接测试
 * @author fidel
 */
public class ServerDemo {
    public static void main(String[] args) throws IOException {
        // 创建一个具有指定端口服务器套接字
        ServerSocket serverSocket = new ServerSocket(18720);
        Socket socket;
        BufferedReader bufferedReader;
        BufferedWriter bufferedWriter;
        {
            // 监听并接受与该套接字的连接
            socket = serverSocket.accept();
            /*
             * 以套接字的输出流构造一个数据输出流
             * 数据输出流允许应用程序以可移植的方式将原始的Java数据类型写入输出流
             * 应用程序可以使用数据输入流将数据读回
             */
            bufferedWriter = ClientDemo.getSocketBufferedWriter(socket);
            /*
             * 以套接字的输入流构造一个数据输入流
             * 数据输入流以一种与机器无关的方式从底层输入流中读取原始的Java数据类型
             * 注意：在多线程访问数据输入流的环境下，线程可能不安全
             */
            bufferedWriter.write("客户端通过TCP连接至服务端");
            ClientDemo.flushLine(bufferedWriter);
            bufferedWriter.write("这一段文字由服务端发送。请输入一段文字发送至服务端");
            ClientDemo.flushLine(bufferedWriter);
            bufferedReader = ClientDemo.getSocketBufferedReader(socket);
            bufferedWriter.write("发送至服务端的内容为：" + bufferedReader.readLine());
            ClientDemo.flushLine(bufferedWriter);
        }
        {
            socket = serverSocket.accept();
            bufferedWriter = ClientDemo.getSocketBufferedWriter(socket);
            bufferedWriter.write("客户端通过TCP连接至服务端");
            ClientDemo.flushLine(bufferedWriter);
            bufferedWriter.write("这是一段文字由服务端发送。请输入一段文字发送至服务端");
            ClientDemo.flushLine(bufferedWriter);
            // 从客户端接收一条消息
            bufferedReader = ClientDemo.getSocketBufferedReader(socket);
            bufferedWriter.write("发送至服务端的内容为：" + bufferedReader.readLine());
            ClientDemo.flushLine(bufferedWriter);
        }
        serverSocket.close();
    }
}
